<template>
  <div id="login" v-if="token == null">
    <h2 id="title">管理员登录</h2>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="账号" prop="account">
        <el-input type="text" placeholder="账号" v-model="ruleForm.account" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" placeholder="密码" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input class="cap" placeholder="验证码" v-model="ruleForm.code"></el-input>
        <span class="svg" @click="getCaptcha()" v-html="captcha"></span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div v-else>
    <el-button type='primary' @click="logout">退出登录</el-button>
    <br /> <br />
    <el-upload class="upload-demo" ref="upload" action='http://localhost:3000/upload' multiple
      :headers="{ 'Authorization': 'Bearer ' + token }" :file-list="fileList" list-type="picture"
      :on-change='handleChange' :auto-upload="false" :on-preview="handlePreview" :on-remove="handleRemove">
      <div class="placeholder">
        <!-- <div class="filename"></div> -->
        <el-button slot="trigger" size="small" type="primary" class="webuploader-pick" id="file1">选取图片</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" class="webuploader-pick"
          @click.stop.prevent="submitUpload()">提交</el-button>
      </div>
      <template>

        <ul class="el-upload-list el-upload-list--picture show">
          <li v-for="(item, index) in filePagination" class="el-upload-list__item is-success" tabindex="0" :key=index>
            <div style="width:100%;display: flex;justify-content: space-between;" @click.stop.prevent>

              <div>
                <img style="cursor: pointer;" @click.stop.prevent="scanBigImg(item)"
                  class="el-upload-list__item-thumbnail" :src="item.path">
              </div>

              <div style="margin-right:30px;margin-top:20px;">
                <span class='later'>{{ item.name }}</span>
                <span class='later'>{{ (item.size / 1024).toFixed(2) }} KB</span>
                <span class='later'>{{ item.type }}</span>
                <i style="font-size: 18px;margin-left:20px;padding-top:10px" class="el-icon-delete"
                  @click.stop.prevent="imgDelete(index)">
                </i>
              </div>

            </div>
          </li>
        </ul>
      </template>
    </el-upload>
    <br />
    <div class="block" v-show='show'>
      <el-pagination layout="prev, pager, next" :total="length" @current-change="changePage"
        :current-page.sync="currentPage">
      </el-pagination>
    </div>

    <el-button type="button" @click="showUser()">用户管理</el-button>

    <el-dialog title="用户管理" :visible.sync="outerVisible">
      <el-table :data="userShowArray">

        <el-table-column prop="name" label="姓名" align="center" width="90">
          <template slot-scope="scope">
            <span v-show="!scope.row.isEdit">{{ scope.row.name }}</span>
            <el-input v-show="scope.row.isEdit" v-model="scope.row.name"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="telephone" label="电话" align="center" width="120">
          <template slot-scope="scope">
            <span v-show="!scope.row.isEdit">{{ scope.row.telephone }}</span>
            <el-input v-show="scope.row.isEdit" v-model="scope.row.telephone"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center" width="120">
          <template slot-scope="scope">
            <span v-show="!scope.row.isEdit">{{ scope.row.email }}</span>
            <el-input v-show="scope.row.isEdit" v-model="scope.row.email"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" align="center" width="135">
          <template slot-scope="scope">
            <span v-show="!scope.row.isEdit">{{ scope.row.address }}</span>
            <el-input v-show="scope.row.isEdit" v-model="scope.row.address"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="118">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleSave(scope.$index, scope.row)">保存</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-dialog width="38%" title="添加信息" :visible.sync="innerVisible" append-to-body>
        <el-form :model="form">
          <el-form-item label="姓名:" :label-width="formLabelWidth">
            <el-input v-model="form.name" style="width:300px" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话:" :label-width="formLabelWidth">
            <el-input v-model="form.telephone" style="width:300px" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" :label-width="formLabelWidth">
            <el-input v-model="form.email" style="width:300px" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="地址:" :label-width="formLabelWidth">
            <el-input v-model="form.address" style="width:300px" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm()">确认添加</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer" style="flex-direction: row;">

        <span class="block" v-show='userShow'>
          <el-pagination style="display:inline-block;float: left;" layout="prev, pager, next" :total="userLength"
            @current-change="changeUserPage" :current-page.sync="currentUserPage" :page-size='5'>
          </el-pagination>
        </span>

        <span>
          <el-button @click="outerVisible = false">关 闭</el-button>
          <el-button type="primary" @click="addUser()">添加信息</el-button>
        </span>
      </div>

    </el-dialog>


  </div>
</template>
<script>
import axios from "axios";
axios.defaults.withCredentials = true;

export default {
  data() {
    var checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    var validateAccount = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        account: "", // 账号
        pass: "", // 密码
        code: "", // 输入的验证码
      },
      rules: {
        account: [{ validator: validateAccount, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }],
        code: [{ validator: checkCode, trigger: "blur" }],
      },
      show: false,
      length: 0,
      captcha: "",
      fileList: [],
      filePagination: [],
      fileShow: [],
      token: localStorage.getItem('token'),
      currentPage: 1,
      outerVisible: false,
      innerVisible: false,
      userBase: [],
      form: {
        name: '',
        telephone: '',
        email: '',
        address: ''
      },
      formLabelWidth: '90px',
      showInput: false,
      currentUserPage: 1,
      userLength: 0,
      userShow: false,
      userShowArray: []
    };
  },
  methods: {
    async submitForm(formName) {
      try {
        await this.$refs[formName].validate();
        const res = await this.$axios.post("/getUser", {
          username: `${this.ruleForm.account}`,
          pwd: `${this.ruleForm.pass}`,
          captcha: `${this.ruleForm.code}`,
        });
        const token = res.token;
        localStorage.setItem('token', token);
        this.token = token;
        if (res.msg == "登录成功") {
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
          this.getCaptcha();
        }
      } catch (error) {
        this.$message.error("有未填写的内容");
        return false;
      }
    },
    async getCaptcha() {
      const res = await this.$axios.get("captcha");
      this.captcha = res.img;
    },
    logout() {
      localStorage.removeItem('token')
      location.reload()
    },
    async submitUpload() {
      let fd = new FormData();
      fd.append("name", this.name);
      this.fileList.forEach(item => {
        fd.append("files", item.raw);
        // console.log(item.raw)
      })
      await this.$axios.post('/upload', fd).then(res => {
        if (res.code === 200) {
          this.getImg()
          this.$message.success('上传成功')
        } else {
          this.$message.error('上传失败')
        }
      })
    },
    pagnation(e) {
      this.filePagination = []
      if (this.fileShow.length >= 10 * e) {
        for (let i = (e - 1) * 10; i < e * 10; i++) {
          this.filePagination.push(this.fileShow[i])
        }
      } else {
        for (let i = (e - 1) * 10; i < this.fileShow.length; i++) {
          this.filePagination.push(this.fileShow[i])
        }
      }
    },
    async getImg() {
      let res = await this.$axios.get('/files');
      this.fileShow = res
      this.pagnation(1)
      if (this.fileShow.length != 0) {
        this.show = true
      } else {
        this.show = false
      }
      this.length = this.fileShow.length
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    changePage(e) {
      this.pagnation(e)
    },
    scanBigImg(e) {
      console.log(e)
    },
    async imgDelete(index) {
      await this.$axios.delete('/del', { params: { fileName: this.filePagination[index].name } })
      if (this.filePagination.length == 1 && this.fileShow != []) {
        this.getImg()
      } else {
        this.fileShow = await this.$axios.get('/files');
        this.pagnation(this.currentPage)
      }
    },
    changeUserPage(e) {
      this.userPagnation(e)
    },
    userPagnation(e) {
      this.userShowArray = []
      if (this.userBase.length >= 5 * e) {
        for (let i = (e - 1) * 5; i < e * 5; i++) {
          this.userShowArray.push(this.userBase[i])
        }
      } else {
        for (let i = (e - 1) * 5; i < this.userBase.length; i++) {
          this.userShowArray.push(this.userBase[i])
        }
      }
    },
    async showUser() {
      this.outerVisible = true;
      const users = await this.$axios.get("/user");
      this.userBase = users
      this.userPagnation(1)
      this.currentUserPage = 1
      if (this.userBase.length != 0) {
        this.userShow = true
      } else {
        this.userShow = false
      }
      this.userLength = this.userBase.length
    },
    async addUser() {
      this.innerVisible = true;
    },
    async confirm() {
      this.innerVisible = false;
      const result = await this.$axios.post("/addUser", {
        name: `${this.form.name}`,
        telephone: `${this.form.telephone}`,
        email: `${this.form.email}`,
        address: `${this.form.address}`
      });
      if (result.code == 200) {
        this.$message.success('添加成功')
        if (this.userShowArray.length < 5) {
          this.userShowArray.push(this.form)
        }
        this.userBase.push(this.form)
        this.userLength = this.userBase.length
        this.form = {
          name: '',
          telephone: '',
          email: '',
          address: ''
        }
      } else {
        this.$message.error('添加失败')
      }
    },
    handleEdit(index) {
      this.$set(this.userShowArray[index], 'isEdit', true)
    },
    async handleSave(index, row) {
      if (this.userShowArray[index].isEdit) {
        this.$set(this.userShowArray[index], 'isEdit', false)
        delete row.isEdit
        row.index = index + (this.currentUserPage - 1) * 5
        await this.$axios.post('/alterUser', row)
        this.$message.success('修改成功')
      }
    },
    handleDelete(index, row) {
      this.$confirm(`确定删除${row.name}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      }).then(async () => {
        const item = index + (this.currentUserPage - 1) * 5
        await this.$axios.delete('/deleteUser', { params: { deleteIndex: item } })
        this.$message.success('删除成功')
        this.userShowArray.splice(index, 1);
        this.userBase.splice(item, 1)
        console.log(this.userShowArray)
        console.log(this.userBase)
        this.userLength = this.userBase.length
        if (this.userShowArray.length == 0 && this.userBase != []) {
          this.userPagnation(this.currentUserPage - 1)
        }
      });
    }
  },
  mounted() {
    this.getCaptcha();
    this.getImg();
  },
};

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#login {
  width: 400px;
  margin-top: 120px;
  background: url(bg.jpg) no-repeat;
  background-size: 100% 160%;
}

#title {
  margin-left: 80px;
  font-weight: bold;
  color: yellow;
}

.later {
  margin-right: 30px;
}

.cap {
  width: 175px;
}

.svg {
  float: right;
}

.placeholder {
  width: 800px;
  border: 3px dashed #e6e6e6;
  min-height: 238px;
  padding-top: 158px;
  text-align: center;
  color: #cccccc;
  font-size: 18px;
  position: relative;
}

.webuploader-pick {
  font-size: 18px;
  background: #00b7ee;
  border-radius: 3px;
  line-height: 44px;
  padding: 0 30px;
  color: #fff;
  display: inline-block;
  margin: 20px auto;
  cursor: pointer;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}

.webuploader-pick {
  position: relative;
  display: inline-block;
  background: #00b7ee;
  border: 1px solid #99D3F5;
  border-radius: 4px;
  padding: 10px 18px;
  overflow: hidden;
  color: white;
  text-decoration: none;
  text-indent: 0;
  line-height: 20px;
  font-size: 12px;
  cursor: pointer;
}

.webuploader-pick input {
  position: absolute;
  right: 0;
  top: 0;
  opacity: 0;
  padding: 10px 18px;
  cursor: pointer;
}

.webuploader-pick:hover {
  background: #AADFFD;
  border-color: #78C3F3;
  color: red;
  text-decoration: none;
}

:deep(.el-upload-list.el-upload-list--picture) {
  display: none !important;
}

.el-upload-list.el-upload-list--picture.show {
  display: block !important;
}
</style>
